import React from 'react'
import {Route,Switch,withRouter,Redirect} from 'react-router-dom'
//withRouter用于向下传递props
import {observer,inject} from "mobx-react";
import NoPrivate from '../../component/NoPrivate/NoPrivate'
@inject('userStore')
@observer
class PrivateRoute extends React.Component {
    routerFun=(routerList)=>{
        //console.log(routerList)
        return routerList.map((route)=>{
            if(route.meta&&route.meta.require){//需要验证登录
                if(this.props.userStore.userMessage.isLogin){//判断是否登录
                    const permissions = this.props.userStore.userMessage.permissions
                    const role = route.role
                    if(role.includes(permissions)){
                        if(route.children){
                            return  <Route key={route.name} path={route.path} render={()=>
                                <route.component key={route.name} {...this.props}>
                                    {this.routerFun(route.children)}
                                    <Route key={route.name} exact path={route.path} render={()=><Redirect to={route.redirect}/>}/>
                                </route.component>
                            }/>
                        }else {
                            return  <Route key={route.name} exact path={route.path} component={route.component}/>
                        }
                    }else {
                        return <Route key={route.name} exact path={route.path} component={NoPrivate}/>
                    }

                }else {
                    return <Redirect key={route.name} to='/Login'/>
                }
            }else if(route.redirect){//判断该路由是否需要重定向
                return <Route key={route.name} exact path={route.path} render={()=><Redirect to={route.redirect}/>}/>
            }else {//不需要登录
                return <Route key={route.name} path={route.path} exact component={route.component}/>
            }
        })
    }

    render() {
        let {routerList} = this.props
        return (
            <Switch>
                {this.routerFun(routerList)}
            </Switch>
        )
    }
}

export default withRouter(PrivateRoute)